package com.sixmac.controller;

import com.sixmac.annotation.AuthUser;
import com.sixmac.core.annotation.Validator;
import com.sixmac.core.base.model.Format;
import com.sixmac.core.constant.ConstConfig;
import com.sixmac.core.constant.Constant;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.support.Convert;
import com.sixmac.model.ClienUser;
import com.sixmac.module.vo.FileVo;
import com.sixmac.utils.FileUtil;
import com.sixmac.utils.UploadUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * UserController
 * 2018-06-09 09:57:44
 *
 * @author Blade
 */
@Controller
@ResponseBody
public class UserController extends ApiController {


    /**
     * @api {post} /api/editUser   修改用户信息
     * @apiName user.editUser
     * @apiGroup user
     * @apiParam {String}  token  token
     * @apiParam {String}  address  地址
     * @apiParam {String} grade 班级
     * @apiParam {String} headimg 头像
     * @apiParam {String}  identity  身份证
     * @apiParam {String} name 用户名
     * @apiParam {String} nickname 昵称
     * @apiParam {String}  phone  手机号码
     * @apiParam {String} school 学校
     * @apiParam {String} studentId 学号
     * @apiError {Integer} 1
     */
    @AuthUser(isGuess = false)
    @RequestMapping("/editUser")
    public AjaxResult editUsre(ClienUser user, String address, String grade, String headimg, String identity, String name, String nickname, String phone, String school, String studentId) {
        ClienUser uu = new ClienUser();
        uu.setId(user.getId());
        uu.setAddress(address);
        uu.setGrade((grade));
        uu.setHeadimg(headimg);
        uu.setIdentity(identity);
        uu.setName(name);
        uu.setNickname(nickname);
        uu.setPhone(phone);
        uu.setSchool(school);
        uu.setStudentId(studentId);

        boolean f = Blade.create(ClienUser.class).update(uu);
        if (f) {
            return success("修改成功");
        }
        return error("修改失败");
    }

    /**
     * @api {post} /api/uploadImg   上传图片
     * @apiName user.uploadImg
     * @apiGroup user
     * @apiDescription 图片上传(适用多图片)
     * @apiParam {File}         files   图片 可多传 (多文件名，例：files，files，files，)（必传）
     * @apiSuccess {String}     name    图片名称
     * @apiSuccess {String}     path    图片路径
     */
    @RequestMapping("uploadImg")
    public AjaxResult uploadImage(MultipartRequest multipartRequest) {
        AjaxResult res = new AjaxResult();
        // 获取图片组
        List<MultipartFile> fileList = multipartRequest.getFiles("files");
        if (null == fileList || fileList.size() == 0) {
            return res.addError("上传图片错误");
        }

        for (MultipartFile iList : fileList) {
            // 验证图片格式
            String originalFileName = iList.getOriginalFilename().toLowerCase();
            String fileType = originalFileName.substring(originalFileName.lastIndexOf("."));

            List<String> list = new ArrayList<>();
            list.add(".jpg");
            list.add(".gif");
            list.add(".jpeg");
            list.add(".png");
            list.add(".bmp");

            if (!list.contains(fileType)) {
                return res.addError("格式错误");
            }
        }

        List<FileVo> prsList = new ArrayList<FileVo>();
        // 在获取的系统时间后面加上数组下标，防止会有同名的图片生成
        int i = 0;

        for (MultipartFile iList : fileList) {
            MultipartFile file = iList;
            FileVo prs = new FileVo();
            String name = String.valueOf(System.currentTimeMillis()) + i;
            try {
                InputStream inputStream = file.getInputStream();
                String origFileName = file.getOriginalFilename(); //原始名称,如aa.jpg
                String ext = FileUtil.getFileExt(origFileName); //后缀，如jpg
                String newFileName = name + ext;
                String uploadPath = UploadUtil.getImagesUpladPath(); //生成日期目录 image/2014/7/
                String desFilePathName = uploadPath + name + ext;//完整文件名称 image/2014/7/221144144554.jpg
                File theFile = new File(ConstConfig.UPLOADFILE_PATH, desFilePathName); //生成的文件对象

                FileUtils.copyInputStreamToFile(inputStream, theFile);

                i++;

                prs.setName(newFileName);
                prs.setPath(ConstConfig.UPLOAD_PATH + desFilePathName);
            } catch (IOException e) {
                e.printStackTrace();
            }

            prsList.add(prs);

        }
        return res.setData(getData("list", prsList));
    }

    /**
     * @api {post} /api/editPassword   修改密码
     * @apiName user.editPassword
     * @apiGroup user
     * @apiDescription 修改密码
     * @apiParam {String}         studentId   学号
     * @apiParam {String}         oldPassword   旧密码
     * @apiParam {String}         newPassword   新密码
     */
    @RequestMapping("/editPassword")
    @Validator(name = {"studentId", "oldPassword", "newPassword"}, format = {Format.NOT_NULL, Format.NOT_NULL, Format.NOT_NULL})
    public AjaxResult editPassword(String studentId, String oldPassword, String newPassword) {
        ClienUser user = Blade.create(ClienUser.class).findFirstBy("studentId = #{studentId}", getCMap().put("studentId", studentId));
        if (user == null) {
            return error("学号找不到");
        }
        if (!user.getPassword().equals(oldPassword)) {
            return error("密码错误");
        }
        ClienUser clienUser = new ClienUser();
        clienUser.setPassword(newPassword);
        return success("修改成功");

    }


}
